package com.dd.cloud.user.service.consule.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.common.constants.ConsultConstants;
import com.dd.cloud.common.enums.ZkExceptionEnum;
import com.dd.cloud.common.exception.ZekeException;
import com.dd.cloud.common.interceptor.UserInterceptor;
import com.dd.cloud.common.vo.LoginInfo;
import com.dd.cloud.user.entity.consult.ConsultMedicalRecord;
import com.dd.cloud.user.entity.consult.ConsultSubscribe;
import com.dd.cloud.user.entity.doctor.DoctorDetail;
import com.dd.cloud.user.mapper.consult.ConsultMedicalRecordMapper;
import com.dd.cloud.user.req.consult.ConsultMedicalRecordCreateReq;
import com.dd.cloud.user.req.consult.ConsultMedicalRecordPageReq;
import com.dd.cloud.user.res.consult.ConsultMedicalRecordDetailRes;
import com.dd.cloud.user.res.consult.ConsultMedicalRecordPageRes;
import com.dd.cloud.user.service.consule.IConsultMedicalRecordService;
import com.dd.cloud.user.service.consule.IConsultSubscribeService;
import com.dd.cloud.user.service.doctor.IDoctorDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author Lx
 * @version 1.0
 */
@Slf4j
@Service
public class ConsultMedicalRecordServiceImpl extends ServiceImpl<ConsultMedicalRecordMapper, ConsultMedicalRecord> implements IConsultMedicalRecordService {
    @Autowired
    private IConsultSubscribeService consultSubscribeService;
    @Autowired
    private IDoctorDetailService doctorDetailService;

    /**
     * 创建问诊电子病历
     *
     * @param req
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createConsultMedicalRecord(ConsultMedicalRecordCreateReq req) {
        ConsultSubscribe cs = consultSubscribeService.getById(req.getConsultId());
        if (cs == null) {
            throw new ZekeException(400, "问诊记录不存在");
        }
        if (cs.getType() == ConsultConstants.Type.CONSULT) {
            throw new ZekeException(400, "在线咨询无法创建电子病历");
        }
        QueryWrapper<ConsultMedicalRecord> qw = new QueryWrapper<>();
        qw.lambda().eq(ConsultMedicalRecord::getConsultId, req.getConsultId());
        qw.lambda().ne(ConsultMedicalRecord::getStatus, ConsultConstants.ConsultMedicalRecordStatus.DEL);
        ConsultMedicalRecord cmr = getOne(qw);
        if (cmr == null) {
            cmr = new ConsultMedicalRecord();
        } else {
            if (cmr.getStatus() == ConsultConstants.ConsultMedicalRecordStatus.NORMAL) {
                throw new ZekeException(400, "已填写电子病历,无法重复填写");
            }
        }
        BeanUtils.copyProperties(req, cmr);
        cmr.setCreateDate(LocalDateTime.now());
        boolean flag = saveOrUpdate(cmr);
        if (!flag) {
            throw new ZekeException(ZkExceptionEnum.ADD_ERROR);
        }
    }

    /**
     * 查询问诊电子病历详情
     *
     * @param consultId
     * @return
     */
    @Override
    public ConsultMedicalRecordDetailRes queryConsultMedicalRecordDetail(Integer consultId) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo().get();
        loginInfo.setType(LoginInfo.UserType.DOCTOR);
        ConsultSubscribe consultSubscribe = consultSubscribeService.getById(consultId);
        QueryWrapper<ConsultMedicalRecord> qw = new QueryWrapper<>();
        qw.lambda().eq(ConsultMedicalRecord::getConsultId, consultId);
        if (loginInfo.getType() == LoginInfo.UserType.DOCTOR) {
            qw.lambda().ne(ConsultMedicalRecord::getStatus, ConsultConstants.ConsultMedicalRecordStatus.DEL);
        } else if (loginInfo.getType() == LoginInfo.UserType.PATIENT || loginInfo.getType() == LoginInfo.UserType.ADMIN) {
            qw.lambda().eq(ConsultMedicalRecord::getStatus, ConsultConstants.ConsultMedicalRecordStatus.NORMAL);
        }
        ConsultMedicalRecord cmr = this.getOne(qw);
        ConsultMedicalRecordDetailRes res = new ConsultMedicalRecordDetailRes();
        if (consultSubscribe != null) {
            LambdaQueryWrapper<DoctorDetail> doctorWrapper = new LambdaQueryWrapper<>();
            doctorWrapper.eq(DoctorDetail::getDoctorId, consultSubscribe.getDoctorId());
            DoctorDetail doctorDetail = doctorDetailService.getOne(doctorWrapper);
            res.setConsultId(consultSubscribe.getId())
                    .setAim(consultSubscribe.getAim())
                    .setPatientName(consultSubscribe.getPatientName())
                    .setPatientSex(consultSubscribe.getPatientSex())
                    .setPatientBirthDate(consultSubscribe.getPatientBirthDate())
                    .setType(consultSubscribe.getType())
                    .setMedId(consultSubscribe.getMedId())
                    .setVisitType(consultSubscribe.getVisitType())
                    .setFirstMechanName(consultSubscribe.getFirstMechanName())
                    .setCreateDate(consultSubscribe.getDay());
            if (doctorDetail != null) {
                res.setDoctorName(doctorDetail.getName())
                        .setWorkCard(doctorDetail.getWorkCard())
                        .setDepartment(doctorDetail.getDepartment());
            }
        }
        if (cmr != null) {
            res.setZyCode(cmr.getZyCode())
                    .setZyName(cmr.getZyName())
                    .setDialecticalDiagnosis(cmr.getDialecticalDiagnosis())
                    .setChiefComplaint(cmr.getChiefComplaint())
                    .setAllergyHistory(cmr.getAllergyHistory())
                    .setId(cmr.getId())
                    .setPhysicalCheck(cmr.getPhysicalCheck())
                    .setAuxiliaryCheck(cmr.getAuxiliaryCheck())
                    .setHandleOpinion(cmr.getHandleOpinion())
                    .setRemark(cmr.getRemark())
                    .setStatus(cmr.getStatus());
        }
        return res;
    }

    /**
     * 查询问诊电子病历列表
     *
     * @param req
     * @return
     */
    @Override
    public IPage<ConsultMedicalRecordPageRes> queryConsultMedicalRecordPage(ConsultMedicalRecordPageReq req) {
        IPage<ConsultMedicalRecordPageRes> iPage = req.pagePojo();
        iPage = getBaseMapper().queryConsultMedicalRecordPage(iPage, req);
        return iPage;
    }
}
